#!/bin/bash

# project name.
PROJECT_NAME=stevejrong-atlanta

# branch name by project.
BRANCH_NAME=1.0.6
# previous branch name by project.
PREVIOUS_BRANCH_NAME=1.0.5

# docker registry domain(Singapore of southeast zone)
DOCKER_REGISTRY_DOMAIN=registry.ap-southeast-1.aliyuncs.com
DOCKER_NAMESPACE=stevejrong-c2c
# expose port for this app in docker
DOCKER_ENTRYPORT=8100

echo ==================================================
echo Script startup for publishing $PROJECT_NAME
echo ==================================================

echo -e "-------------------- ready go!\n"

# clean old docker images
echo "-------------------- deleting old docker images"
sudo docker rmi -f $DOCKER_REGISTRY_DOMAIN/$DOCKER_NAMESPACE/$PROJECT_NAME:$BRANCH_NAME
sudo docker rmi -f $DOCKER_REGISTRY_DOMAIN/$DOCKER_NAMESPACE/$PROJECT_NAME:$PREVIOUS_BRANCH_NAME
# clean images when image name like none
docker rmi $(docker images | grep "^<none>" | awk "{print $3}")
echo "-------------------- delete complete.\n"
sleep 5

# pull new docker images
echo "-------------------- deleting old docker images"
sudo docker pull $DOCKER_REGISTRY_DOMAIN/$DOCKER_NAMESPACE/$PROJECT_NAME:$BRANCH_NAME
echo "-------------------- delete complete.\n"
sleep 5

echo "-------------------- stopping old docker instance"
docker stop $PROJECT_NAME-main
echo -e "-------------------- stop success.\n"
sleep 5

echo "-------------------- removing old docker instance"
docker rm $PROJECT_NAME-main
echo -e "-------------------- remove success.\n"
sleep 5

echo "-------------------- creating log directory"
mkdir /home/app-logs/$PROJECT_NAME/
chmod -R 777 /home/app-logs/$PROJECT_NAME/
echo -e "-------------------- create success.\n"
sleep 5

echo "-------------------- deploying with docker image"
docker run -p $DOCKER_ENTRYPORT:$DOCKER_ENTRYPORT -d --name $PROJECT_NAME-main --restart always --privileged=true -v /home/app-logs/$PROJECT_NAME:/home/web/logs:rw $DOCKER_REGISTRY_DOMAIN/$DOCKER_NAMESPACE/$PROJECT_NAME:$BRANCH_NAME
echo -e "-------------------- deploying with docker image success.\n"

echo =================================================
echo Publish $PROJECT_NAME version $BRANCH_NAME completed!
echo =================================================